package com.liyghting.mutildb.config;

import javax.sql.DataSource;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
@MapperScan(basePackages = { MultiBdbMybatisConfig.BASE_DAO_SCAN }, sqlSessionFactoryRef = "bdbSqlSessionFactory")
public class MultiBdbMybatisConfig {

	protected static final String BASE_DAO_SCAN = "com.liyghting.mutildb.bdb";

	@Bean
	@ConfigurationProperties(prefix = "bdbDataSource")
	public DataSourceProperties bdbDataSourceProperties() {
		DataSourceProperties bdbDataSourceProperties = new DataSourceProperties();
		return bdbDataSourceProperties;
	}

	@Bean
	@ConditionalOnBean(name = "bdbDataSourceProperties")
	public DataSource bdbDataSource() {
		DataSourceProperties bdbDataSourceProperties = bdbDataSourceProperties();
		return bdbDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
	}

	@Bean
	@ConditionalOnBean(name = "bdbDataSource")
	public DataSourceTransactionManager bdbTransactionManager() {
		DataSource bdbDataSource = bdbDataSource();
		return new DataSourceTransactionManager(bdbDataSource);
	}

	@Bean
	@ConfigurationProperties("bdbMybatis")
	public MybatisProperties bdbMybatisProperties() {
		MybatisProperties bdbMybatisProperties = new MybatisProperties();
		return bdbMybatisProperties;
	}

	@Bean
	@ConditionalOnBean(name = { "bdbMybatisProperties", "bdbDataSource" })
	public SqlSessionFactory bdbSqlSessionFactory() throws Exception {
		MybatisProperties bdbMybatisProperties = bdbMybatisProperties();
		DataSource bdbDataSource = bdbDataSource();
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(bdbDataSource);
		sessionFactory.setMapperLocations(bdbMybatisProperties.resolveMapperLocations());
		sessionFactory.setConfiguration(bdbMybatisProperties.getConfiguration());
		return sessionFactory.getObject();
	}
}
